<!-- 活动信息收集 -->
<template>
  <div class="bg-white _p-20">
    <div class="disFlxAC _mb-24 title">
      <span class="fz-16 fw-700 _mr-8" style="color: #1D2129;">信息收集</span>
      <span class="disFlxAC">
        拖动
        <img class="width-1.6 height-1.6 _ml-4 _mr-4" src="@/assets/icons/drag.png" alt="" />
        可调整字段顺序
      </span>
    </div>
    <div class="from-container disFlx ">
      <div style="flex: 1;" class="_mr-24">
        <div class="_mb-30">
          <span class="fz-18 fw-7">报名基本信息：</span>
          <div class="disFlx flexCol  _mt-8">
            <div v-for="(item, index) in basicFieldList" class="disFlxAC  _mb-20">
              <div class=" width-1.6 height-1.6 _mt-30 _mr-16"></div>
              <!-- <img
                class="drag-icon width-1.6 height-1.6 _mt-30 _mr-16"
                src="@/assets/icons/drag.png"
                alt=""
                style="opacity: 0.5;"
              /> -->
              <div style="flex: 1;">
                <div class="disFlxAC  _mb-8">
                  <span v-if="item.isRequired" style="color: #F53F3F;">*</span>
                  <span>{{ item.showName }}</span>
                </div>
                <div class="disFlxAC ">
                  <a-input style="flex: 1;" disabled class="_mr-16" />
                  <div v-if="!disableEditing" class="disFlxAC " style="width: 140px;">
                    <div class="_mr-16">
                      <a-checkbox
                        :checked="!!item.isRequired"
                        :defaultChecked="!!item.isRequired"
                        :disabled="index < 2"
                        @change="e => (item.isRequired = e.target.checked ? 1 : 0)"
                      >
                        必填
                      </a-checkbox>
                    </div>
                    <a-icon
                      type="edit"
                      class="fz-18"
                      @click="handleShowField('edit', item, FieldCategory.FIXED, index)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div>
          <span class="fz-18 fw-7 forbid">活动信息收集：</span>
          <Draggable
            v-model="fieldList"
            filter=".forbid"
            :animation="300"
            handle=".drag-icon"
            class="disFlx flexCol  _mt-8"
            @start="handleStart"
            @end="handleEnd"
          >
            <div v-for="(item, index) in fieldList" class="disFlxAC  _mb-20 " :key="buildUUID()">
              <img
                v-if="!disableEditing"
                class="drag-icon width-1.6 height-1.6 _mt-30"
                src="@/assets/icons/drag.png"
                alt=""
              />
              <div style="flex: 1;">
                <div class="disFlxAC  _mb-8">
                  <span v-if="item.isRequired" style="color: #F53F3F;">*</span>
                  <span class="_mr-4">题目{{ item.sort + 1 }}：{{ item.showName || item.name }}</span>
                  <a-tag v-if="item.dataType" color="blue">用户信息</a-tag>
                </div>
                <div class="disFlxAC ">
                  <a-input disabled style="flex: 1;" class="_mr-16" />
                  <div v-if="!disableEditing" class="disFlxAC " style="width: 140px;">
                    <div v-if="item.itemType !== 'Attachment'" class="_mr-16">
                      <a-checkbox
                        :checked="!!item.isRequired"
                        :defaultChecked="!!item.isRequired"
                        @change="e => (item.isRequired = e.target.checked ? 1 : 0)"
                      >
                        必填
                      </a-checkbox>
                    </div>
                    <a-icon
                      v-if="!item.downLoad"
                      type="edit"
                      class="fz-18 _mr-16"
                      @click="
                        handleShowField(
                          'edit',
                          item,
                          item.dataType ? FieldCategory.CUSTOM : FieldCategory.PREDEFINED,
                          index
                        )
                      "
                    />
                    <a-icon type="delete" class="fz-18" @click="handleDel(index)" />
                  </div>
                </div>
              </div>
            </div>
          </Draggable>
        </div>

        <div class="disFlx flexCenter   _mt-40" v-if="!disableEditing">
          <a-button
            type="primary"
            @click="handleShowField('add', {}, FieldCategory.CUSTOM, fieldList.length)"
            class="_mr-10"
          >
            <a-icon type="plus" />添加自定义字段
          </a-button>
          <a-button type="primary" ghost @click="handleShowJumpQuestion"> <a-icon type="plus" /> 跳题设置 </a-button>
        </div>
      </div>
      <div style="flex: 1;">
        <PresetFields
          ref="presetFieldsRef"
          :disableEditing="disableEditing"
          @del="handleDelField"
          @add="addField"
          @loadingDone="handleLoadingDone"
        ></PresetFields>
      </div>
    </div>

    <AddFieldForm ref="addFieldForm" @addField="addField" @editField="editField" />
    <JumpQuestionRule ref="jumpQuestionRuleRef" @setRuleSuccess="handleSetRuleSuccess" />
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
import SuccessModal from '@/components/SuccessModal/index.vue'
import UploadFileMultiple from '@/components/UploadFile/multiple.vue'
import { FormById, AddOrUpdateForm, FormItemDeleteTip } from '@/api/activity/activity'
import { cancelActivityErr } from '@/utils/codes'
import FormItem from '@/components/FormItem/index.vue'
import Form from '@/components/Form/index.vue'
import AddFieldForm from './AddFieldForm/index.vue'
import { FieldCategory } from './enum'
import JumpQuestionRule from './JumpQuestionRule/index.vue'
import PresetFields from './PresetFields/index.vue'
import { buildUUID } from '@/utils/uuid'
import { cloneDeep } from 'lodash-es'
import { ActivitySettlementStatusEnum } from '@/enums/activity'
export default {
  components: {
    Draggable,
    SuccessModal,
    UploadFileMultiple,
    FormItem,
    Form,
    AddFieldForm,
    JumpQuestionRule,
    PresetFields
  },
  props: {
    activityInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      FieldCategory,
      title: undefined,
      currItem: {
        fieldCategory: '',
        index: -1
      },
      basicFieldList: [],
      fieldList: [],
      copyFieldList: []
    }
  },
  watch: {
    activityInfo: {
      handler() {
        this.getFormById()
      },
      immediate: true
    }
  },
  computed: {
    disabled() {
      return this.activityInfo.activityType === 'other_join' // 协办方
    },
    disableEditing() {
      return (
        [
          ActivitySettlementStatusEnum.PROGRESS,
          ActivitySettlementStatusEnum.SUCCESS,
          ActivitySettlementStatusEnum.PART_SUCCESS
        ].includes(this.activityInfo.settleStatus) || this.disabled
      )
    }
  },
  methods: {
    buildUUID,
    async getFormById() {
      let { data } = await FormById(this.activityInfo.id || 0)
      let list = (data && data.formItemList) || []
      this.title = data.name
      this.fieldList = list.map((item, index) => {
        return {
          ...item,
          sort: index,
          customFormItemAnswerDtoList: item.customFormItemAnswerList || []
        }
      })
      this.basicFieldList = data.defaultFormItemList
      this.resetFieldLibraryIds()
    },
    handleLoadingDone() {
      this.resetFieldLibraryIds()
    },
    resetFieldLibraryIds() {
      if (this.$refs.presetFieldsRef) {
        this.$refs.presetFieldsRef.fieldLibraryIds = this.fieldList
          .filter(item => item.dataType)
          .map(item => item.dataType)
      }
    },
    delFn(index) {
      this.delJumpQuestionRule(index)
      this.resetFieldLibraryIds()
    },

    async handleDel(index) {
      let item = this.fieldList[index]
      //没有id可以直接删除
      if (!item.id || !this.activityInfo.id) {
        this.delFn(index)
        return
      } else {
        let res = await FormItemDeleteTip({
          formItemId: item.id,
          activityId: this.activityInfo.id
        })

        if (res.code === cancelActivityErr) {
          this.$confirm({
            title: '字段删除提示',
            content: h => {
              return h(
                'div',
                JSON.parse(res.msg).map((item, index) => h('p', `${index + 1}：${item}`))
              )
            },
            okText: '依然删除',
            okType: 'danger',
            cancelText: '我再想想',
            onOk: () => {
              this.delFn(index)
            }
          })
        } else {
          this.delFn(index)
        }
      }
    },
    delJumpQuestionRule(index) {
      this.fieldList.forEach((item, itemIndex) => {
        if (itemIndex > index) {
          item.sort = item.sort - 1
        }
        if (item.itemType === 'RadioGroup') {
          if (!item.customFormItemAnswerDtoList) return
          item.customFormItemAnswerDtoList = item.customFormItemAnswerDtoList.map(answerItem => {
            if (!answerItem.relatedFormItemIds) return answerItem
            // 转数组
            const relatedFormItemIds = answerItem.relatedFormItemIds.split(',')
            // 删除跳题
            const delRelatedFormItemIds = relatedFormItemIds.filter(id => Number(id) !== index)

            answerItem.relatedFormItemIds = delRelatedFormItemIds
              .map(id => {
                if (id > index) {
                  return id - 1
                }
                return id
              })
              .join(',')

            return answerItem
          })
        }
      })
      this.fieldList.splice(index, 1)
    },

    editField(form) {
      if (this.currItem.fieldCategory === FieldCategory.FIXED) {
        this.$set(this.basicFieldList, this.currItem.index, form)
      } else {
        this.$set(this.fieldList, this.currItem.index, form)
      }
    },
    addField(form) {
      this.fieldList.push({ ...form, sort: this.fieldList.length })
    },
    handleShowField(type, row, fieldCategory, index) {
      this.currItem.fieldCategory = fieldCategory
      this.currItem.index = index
      let data = JSON.parse(JSON.stringify(row))
      let obj = {
        type: type,
        data: {
          ...data,
          customFormItemAnswerDtoList: data.customFormItemAnswerList || data.customFormItemAnswerDtoList || []
        }
      }
      this.$refs.addFieldForm.show(obj)
    },
    handleShowJumpQuestion() {
      this.$refs.jumpQuestionRuleRef.open(this.fieldList)
    },
    handleSetRuleSuccess(fieldList) {
      this.fieldList = fieldList
    },
    handleDelField(dataType) {
      this.fieldList = this.fieldList.filter(item => !item.dataType || item.dataType !== dataType)
    },

    handleStart() {
      this.copyFieldList = cloneDeep(this.fieldList)
    },
    handleEnd({ oldIndex, newIndex }) {
      this.fieldList.forEach((item, index) => {
        item.sort = index
      })

      // 是否往是上移动
      const isMoveTop = newIndex < oldIndex

      let list = []

      if (isMoveTop) {
        list = this.fieldList.slice(0, oldIndex + 1)
      } else {
        list = this.fieldList
      }

      let isDel = false

      this.fieldList.forEach(item => {
        if (item.itemType === 'RadioGroup') {
          item.customFormItemAnswerDtoList = item.customFormItemAnswerDtoList.map(answerItem => {
            if (!answerItem.relatedFormItemIds) return answerItem

            // 转数组
            const relatedFormItemIds = answerItem.relatedFormItemIds.split(',')

            // 删除跳题（已经移动到自己上面的）
            const delRelatedFormItemIds = relatedFormItemIds.filter(id => {
              if (isMoveTop) {
                if (newIndex < item.sort) {
                  return oldIndex != id
                } else {
                  return item.sort < id
                }
              } else {
                return item.sort < id
              }
            })

            console.log(relatedFormItemIds, delRelatedFormItemIds, item.sort)

            // 判断是有需要清空的跳题
            if (relatedFormItemIds.length > delRelatedFormItemIds.length) {
              isDel = true
            }

            // 更新跳题下标
            const updRelatedFormItemIds = delRelatedFormItemIds.map(id => {
              if (isMoveTop) {
                // 拖拽后，之上的不处理
                if (id < newIndex) return id

                // 被拖拽的
                if (Number(id) === oldIndex) return newIndex

                if (id < oldIndex) return Number(id) + 1
              } else {
                // 拖拽前之上,拖拽后之下不处理
                if (oldIndex > id || newIndex < id) return id

                // 被拖拽的
                if (Number(id) === oldIndex) return newIndex

                if (oldIndex < id) return Number(id) - 1
              }

              return id
            })

            console.log(updRelatedFormItemIds)

            answerItem.relatedFormItemIds = updRelatedFormItemIds.join(',')

            return answerItem
          })
        }
      })

      if (isDel) {
        // 复制一份修改完成的
        const updCompleteFieldList = cloneDeep(this.fieldList)
        // 有要清空的，先还原列表
        this.fieldList = this.copyFieldList
        this.$confirm({
          title: '提示',
          content: `调整排序后，${newIndex + 1}${this.fieldList[newIndex].showName ||
            this.fieldList[newIndex].name}关联的跳题规则将失效，是否调整？`,
          okText: '继续',
          cancelText: '取消',
          onOk: () => {
            // 执行修改
            this.fieldList = updCompleteFieldList
            this.isDel = false
          },
          oncancel: () => {
            this.isDel = false
          }
        })
      }
    },

    //保存表单
    async saveForm() {
      return {
        id: this.activityInfo.id || 0,
        customFormItemList: this.fieldList,
        defaultFormItemList: this.basicFieldList
      }
    }
  }
}
</script>
<style scoped lang="less">
.title {
  border-bottom: solid 1px #e5e6eb;
}
.from-container {
  padding: 24px;
  background-color: #f7f8fa;
}
</style>
